<template>
  <div class="search-page">
    <!-- 头部区域 -->
    <StoreHeader @search="handleHeaderSearch"></StoreHeader>

    <!-- 搜索结果区域 -->
    <div class="search-content">
      <div class="search-container">
        <!-- 筛选条件 -->
        <div class="filter-section">
          <div class="filter-header">
            <h3>筛选条件</h3>
          </div>
          
          <!-- 分类筛选 -->
          <div class="filter-group">
            <div class="filter-title">商品分类</div>
            <div class="filter-tags">
              <el-tag 
                v-for="category in categories" 
                :key="category.id"
                :type="selectedCategory === category.typeId ? 'primary' : 'info'"
                @click="selectCategory(category.typeId)"
                class="filter-tag"
              >
                {{ category.typeName }}
              </el-tag>
            </div>
          </div>
          
          <!-- 价格区间 -->
          <div class="filter-group">
            <div class="filter-title">价格区间</div>
            <div class="price-range">
              <el-input 
                v-model="priceRange.min" 
                placeholder="最低价"
                size="small"
                @blur="handlePriceChange"
              />
              <span>-</span>
              <el-input 
                v-model="priceRange.max" 
                placeholder="最高价"
                size="small"
                @blur="handlePriceChange"
              />
            </div>
          </div>
          
          <!-- 新旧程度 -->
          <div class="filter-group">
            <div class="filter-title">新旧程度</div>
            <div class="filter-tags">
              <el-tag 
                v-for="condition in conditions" 
                :key="condition.value"
                :type="selectedCondition === condition.value ? 'primary' : 'info'"
                @click="selectCondition(condition.value)"
                class="filter-tag"
              >
                {{ condition.label }}
              </el-tag>
            </div>
          </div>
          <el-button type="text" @click="submitFilters">开始筛选</el-button>
          <el-button type="text" @click="resetFilters">清空筛选</el-button>
        </div>
        
        <!-- 搜索结果 -->
        <div class="results-section">
          <!-- 搜索信息 -->
          <div class="search-info">
            <div class="search-summary">
              <span>共找到 {{ totalResults }} 个相关商品</span>
              <span>耗时 {{ searchTime }} ms</span>
            </div>
            
            <!-- 排序方式 -->
            <div class="sort-options">
              <el-select v-model="sortBy" placeholder="排序方式" size="small" @change="handleSortChange">
                <el-option
                  v-for="option in sortOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </div>
          </div>
          
          <!-- 商品列表 -->
          <div class="products-list" v-if="!hasNoResults">
            <el-row :gutter="20">
              <el-col 
                :span="8" 
                v-for="product in productList" 
                :key="product.id"
                class="product-item"
              >
                <ProductCard 
                  :product="product" 
                  @click="goToProductDetail"
                  ></ProductCard>
              </el-col>
            </el-row>
          </div>
          
          <!-- 无数据提示 -->
          <div class="no-results" v-else>
            <el-empty description="暂无相关商品">
              <el-button type="primary" @click="resetFilters">清空筛选条件</el-button>
            </el-empty>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="!hasNoResults">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="totalResults"
              layout="prev, pager, next"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch,computed } from 'vue'
import { useRouter,useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import StoreHeader from '@/components/common/StoreHeader.vue'
import ProductCard from '@/components/common/ProductCard.vue'
//api
import { getList,getListWithoutPage } from '@/api/common/base'
import { getFilterProductList } from '@/api/common/home'

const router = useRouter()
const route=useRoute()

// 搜索关键字
const searchKeyword = ref('')

// 分类数据
const categories = ref([])

// 新旧程度
const conditions = ref([
  { value: 1, label: '全新' },
  { value: 2, label: '九成新' },
  { value: 3, label: '五成新' },
  { value: 4, label: '三成新' },
  { value: 5, label: '破损' }
])

// 排序选项
const sortOptions = ref([
  { value: 0, label: '默认排序' },
  { value: 2, label: '价格从低到高' },
  { value: 1, label: '价格从高到低' },
  { value: 3, label: '最新发布' }
  // { value: 'sales', label: '销量优先' },
  // { value: 'rating', label: '评价优先' }
])

// 筛选条件
const selectedCategory = ref("0")
const selectedCondition = ref("0")
const priceRange = reactive({
  min: '',
  max: ''
})
const sortBy = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const totalResults = ref(128)
const searchTime = ref(42)

// 商品数据
const productList = ref([
  {
    id: 1,
    title: '苹果iPhone 13 全新未拆封',
    price: '4500.00',
    image: 'https://picsum.photos/300/200?random=10',
    location: '学生宿舍1栋',
  },
  {
    id: 2,
    title: 'MacBook Pro 13寸 2020款',
    price: '8500.00',
    image: 'https://picsum.photos/300/200?random=12',
    location: '学生宿舍5栋'
  },
  {
    id: 3,
    title: '高等数学教材 上下册',
    price: '35.00',
    image: 'https://picsum.photos/300/200?random=12',
    location: '学生宿舍12栋',
  },
  {
    id: 4,
    title: '耐克运动鞋 42码 九成新',
    price: '280.00',
    image: 'https://picsum.photos/300/200?random=12',
    location: '学生宿舍8栋',
  },
  {
    id: 5,
    title: '小米空气净化器 2代',
    price: '320.00',
    image: 'https://picsum.photos/300/200?random=14',
    location: '学生宿舍3栋',
  },
  {
    id: 6,
    title: '优衣库羽绒服 男款 L码',
    price: '199.00',
    image: 'https://picsum.photos/300/200?random=13',
    location: '学生宿舍15栋'
  },
  {
    id: 7,
    title: 'Java编程思想 第4版',
    price: '45.00',
    image: 'https://picsum.photos/300/200?random=15',
    location: '学生宿舍7栋'
  },
  {
    id: 8,
    title: '索尼WH-1000XM4 降噪耳机',
    price: '1200.00',
    image: 'https://picsum.photos/300/200?random=16',
    location: '学生宿舍11栋'
  },
  {
    id: 9,
    title: '宜家书桌 全新未使用',
    price: '180.00',
    image: 'https://picsum.photos/300/200?random=17',
    location: '学生宿舍2栋'
  },
  {
    id: 10,
    title: '佳能 EOS 200D 单反相机',
    price: '2200.00',
    image: 'https://picsum.photos/300/200?random=19',
    location: '学生宿舍9栋'
  },
  {
    id: 11,
    title: '北欧风台灯 宿舍必备',
    price: '78.00',
    image: 'https://picsum.photos/300/200?random=20',
    location: '学生宿舍13栋'
  },
  {
    id: 12,
    title: '兰蔻小黑瓶精华 30ml',
    price: '450.00',
    image: 'https://picsum.photos/300/200?random=21',
    location: '学生宿舍6栋'
  }
])

// 处理 StoreHeader 搜索事件
const handleHeaderSearch = (keyword) => {
  searchKeyword.value = keyword
  // 重置分页并重新搜索
  currentPage.value = 1
  submitFilters()
}

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  // 这里可以添加筛选逻辑
}

// 选择新旧程度
const selectCondition = (condition) => {
  selectedCondition.value = condition
  // 这里可以添加筛选逻辑
}

// 价格区间变化
const handlePriceChange = () => {
  // 这里可以添加价格筛选逻辑
}

// 排序变化
const handleSortChange = (value) => {
  sortBy.value = value
  // 这里可以添加排序逻辑
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  submitFilters()
  // 这里可以添加分页逻辑
}

// 重置筛选
const resetFilters = () => {
  selectedCategory.value = "0"
  selectedCondition.value = "0"
  priceRange.min = ''
  priceRange.max = ''
  sortBy.value = 0
  searchKeyword.value = ''
  // 这里可以添加重置逻辑
  submitFilters()
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 返回首页
const goToHome = () => {
  router.push('/')
}

// 提交筛选条件
const submitFilters = async() => {
  // 构造符合后端要求的参数对象
  const filterParams = {
    searchProductName: searchKeyword.value || undefined,
    searchProductMaxPrice: priceRange.max || undefined,
    searchProductMinPrice: priceRange.min || undefined,
    searchProductOld: selectedCondition.value !== "0" ? parseInt(selectedCondition.value) : undefined,
    searchProductType: selectedCategory.value !== "0" ? parseInt(selectedCategory.value) : undefined,
    searchProductPriceOrderDesc: sortBy.value !== 0 ? parseInt(sortBy.value) : undefined
  }
  
  // 打印模拟提交的数据
  let res=await getFilterProductList(currentPage.value,filterParams)
  productList.value = res.data.records
    
    // 更新分页信息
    currentPage.value = res.data.current;
    totalResults.value = res.data.total;
    pageSize.value = res.data.size;
}

const initData = async() => { 
  let res=await getList("/home/overview");
  categories.value=res.data.AllCategories;
}

const hasNoResults = computed(() => {
  return !productList.value || productList.value.length === 0
})

watch(
  [selectedCategory, selectedCondition, currentPage,priceRange,sortBy],
  async([searchProductType, searchProductOld, newcurrentPage,searchProductPrice,searchProductPriceDesc]
  ) => {
  // console.log('筛选参数变化:', searchProductType, searchProductOld,newcurrentPage,searchProductPrice,searchProductPriceDesc)
  // let res=await getFilterProductList(newCurrentPage, { searchProductType: newCategory, searchProductPriceOrderDesc: newSort })
  //   // 根据新的数据结构映射商品数据
  //   productList.value = res.data.records
    
  //   // 更新分页信息
  //   currentPage.value = res.data.current;
  //   totalProducts.value = res.data.total;
  //   pageSize.value = res.data.size;
  
}, { immediate: true })

onMounted(() => {
  // 获取搜索参数
  const query = route.params.keyword
  if (query) searchKeyword.value = query
  submitFilters()
  initData();
})
</script>

<style scoped>
.search-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 头部样式 */
.header {
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
}

/* Logo区域 */
.logo-area {
  flex: 0 0 auto;
}

.logo {
  height: 40px;
  width: auto;
  cursor: pointer;
}

/* 搜索区域 */
.search-area {
  flex: 1;
  max-width: 500px;
  margin-left: 30px;
}

.search-input {
  border-radius: 20px;
}

:deep(.search-input .el-input-group__append) {
  border-radius: 0 20px 20px 0;
  background-color: #409EFF;
  border-color: #409EFF;
}

:deep(.search-input .el-button) {
  color: white;
}

/* 搜索内容区域 */
.search-content {
  padding: 20px 0;
}

.search-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  gap: 20px;
}

/* 筛选条件 */
.filter-section {
  width: 250px;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-header h3 {
  margin: 0;
  font-size: 16px;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
  font-weight: bold;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-tag {
  cursor: pointer;
  margin: 0;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 5px;
}

.price-range span {
  margin: 0 5px;
}

/* 搜索结果 */
.results-section {
  flex: 1;
}

.search-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-summary {
  font-size: 14px;
  color: #666;
}

.search-summary span:first-child {
  margin-right: 15px;
}

/* 商品列表 */
.products-list {
  margin-bottom: 20px;
}

.product-item {
  margin-bottom: 20px;
  cursor: pointer;
}

.product-image {
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 10px;
}

.image {
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 0 5px;
}

.product-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  line-height: 1.4;
}

.product-price {
  font-size: 16px;
  color: #ff5000;
  font-weight: bold;
  margin-bottom: 8px;
}

.product-location {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.product-location i {
  margin-right: 3px;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 图片占位符 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

:deep(.image-slot .el-icon) {
  font-size: 36px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }
  
  .filter-section {
    width: 100%;
  }
  
  .search-info {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
/* 无数据提示样式 */
.no-results {
  background-color: white;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.no-results .el-empty) {
  padding: 20px 0;
}
</style>